package com.joint.web.action.com;


import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.bean.Result;
import com.fz.us.base.util.Collections3;
import com.fz.us.base.util.LogUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.entity.*;
import com.joint.base.service.*;
import com.joint.base.util.StringUtils;

import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.persistence.entity.HistoricTaskInstanceEntity;
import org.activiti.engine.impl.persistence.entity.HistoricVariableInstanceEntity;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by hpj on 2014/9/16.
 */
@ParentPackage("com")
public class AjaxDialogAction extends BaseFlowAction {

    @Resource
    private UsersService usersService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private PostService postService;
    @Resource
    private PowerService powerService;
    @Resource
    private DutyService dutyService;
    @Resource
    private GroupService groupService;
    @Resource
    private TaskService taskService;
    @Resource
    private RoleService roleService;

    @Resource
    private BusinessConfigService businessConfigService;


    /**
     * 党政模块定义的属性
     */
    private String dictName;    //字典名称
    private String index;       //索引
    private String parentId;    //父类ID
    private String departId;    //部门Id
    private String str;         //拼接字符串
    private String powerId;     //职权ID
    private String result;      //拼接字符串
    private String usersId;     //用户对象
    private String payDate;     //时间对象
    private String keyId;


    private String flowName;

    private String clientId;

    /**是否是模型选择*/
    private String isModal;
    /**
     * 对话框关键字参数
     */
    private String key;

    /**
     * 申请培训
     * @return
     */
    private String depId;

    /**
     * 培训
     */
    private String departmentId;

    /**
     * 多选标志
     */
    private String more;

    /**
     *流程引擎标志
     */
    private String businessKey;

    public String getClientId() {
        return clientId;
    }

    public void setClientId(String clientId) {
        this.clientId = clientId;
    }


    /**
     * 选择某公司下的用户
     * @return
     */
    public String usersDlg(){
        pager = new Pager(0);
        pager.setOrderBy("no");
        pager.setOrderType(BaseEnum.OrderType.asc);
        Company com = usersService.getCompanyByUser();
        Map<String,Object> pMap = Maps.newHashMap();
        pMap.put("adminType","1");
        pager = usersService.findByPagerAndCompany(pager, null, com, pMap);
        List<Users> usersList = (List<Users>) pager.getList();
        Map<String,Object> rMap ;
        Map<String,Object> data = Maps.newHashMap();
        List<JSONObject> dataRows = Lists.newArrayList();

        for(Users users : usersList){
            rMap = Maps.newHashMap();
            rMap.put("name", users.getName());
            rMap.put("id",users.getId());
            if(StringUtils.isNotEmpty(keyIds)){
                if(StringUtils.contains(keyIds, users.getId())){
                    rMap.put("checked","checked");
                }
            }
            dataRows.add(JSONObject.fromObject(rMap));
        }

        data.put("data", JSONArray.fromObject(dataRows));
        Result rs = new Result(200,"操作成功",data);
        return ajaxHtmlAppResult(rs);
    }

    /**
     * 选择用户
     * @return
     */
    public String userDlg(){

        List<Users> usersList = (List<Users>) usersService.findByPagerAndStates(new Pager(0), new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList();
        Map<String,Object> rMap ;
        Map<String,Object> data = Maps.newHashMap();
        List<JSONObject> dataRows = Lists.newArrayList();

        for(Users users : usersList){
            rMap = Maps.newHashMap();
            rMap.put("name", users.getName());
            rMap.put("id",users.getId());
            if(StringUtils.isNotEmpty(keyIds)){
                if(StringUtils.contains(keyIds, users.getId())){
                    rMap.put("checked","checked");
                }
            }
            dataRows.add(JSONObject.fromObject(rMap));
        }

        data.put("data", JSONArray.fromObject(dataRows));
        Result rs = new Result(200,"操作成功",data);
        return ajaxHtmlAppResult(rs);
    }

    /**
     * 选择角色
     * @return
     */
    public String roleDlg(){

        List<Role> roleList = (List<Role>) roleService.findByPagerAndStates(new Pager(0), new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList();
        Map<String,Object> rMap ;
        Map<String,Object> data = Maps.newHashMap();
        List<JSONObject> dataRows = Lists.newArrayList();

        for(Role role : roleList){
            rMap = Maps.newHashMap();
            rMap.put("name", role.getName());
            rMap.put("id",role.getId());
            if(StringUtils.isNotEmpty(keyIds)){
                if(StringUtils.contains(keyIds, role.getId())){
                    rMap.put("checked","checked");
                }
            }
            dataRows.add(JSONObject.fromObject(rMap));
        }

        data.put("data", JSONArray.fromObject(dataRows));
        Result rs = new Result(200,"操作成功",data);
        return ajaxHtmlAppResult(rs);
    }

    /**
     * 选择部门
     * @return
     */
    public String departDlg(){
        pager = new Pager();
        pager.setOrderBy("no");
        pager.setOrderType(BaseEnum.OrderType.asc);
        List<Department> departmentList = (List<Department>) departmentService.findByPagerAndStates(pager, new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList();
        Map<String,Object> rMap ;
        Map<String,Object> data = Maps.newHashMap();
        List<JSONObject> dataRows = Lists.newArrayList();
        for(Department department : departmentList){
            rMap = Maps.newHashMap();
            rMap.put("name", department.getName());
            rMap.put("id",department.getId());
            if(StringUtils.isNotEmpty(keyIds)){
                if(StringUtils.contains(keyIds, department.getId())){
                    rMap.put("checked","checked");
                }
            }
            dataRows.add(JSONObject.fromObject(rMap));
        }

        data.put("data", JSONArray.fromObject(dataRows));
        Result rs = new Result(200,"操作成功",data);
        return ajaxHtmlAppResult(rs);
    }

    /**
     * 选择岗位
     * @return
     */
    public String postDlg(){
        List<Post> postList = (List<Post>) postService.findByPagerAndStates(new Pager(0), new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList();
        Map<String,Object> rMap ;
        Map<String,Object> data = Maps.newHashMap();
        List<JSONObject> dataRows = Lists.newArrayList();
        for(Post post : postList){
            rMap = Maps.newHashMap();
            rMap.put("name", post.getName());
            rMap.put("id",post.getId());
            if(StringUtils.isNotEmpty(keyIds)){
                if(StringUtils.contains(keyIds, post.getId())){
                    rMap.put("checked","checked");
                }
            }
            dataRows.add(JSONObject.fromObject(rMap));
        }

        data.put("data", JSONArray.fromObject(dataRows));
        Result rs = new Result(200,"操作成功",data);
        return ajaxHtmlAppResult(rs);
    }

    /**
     * 选择群组
     * @return
     */
    public String groupDlg(){
        List<Group> groupList = (List<Group>) groupService.findByPagerAndStates(new Pager(0), new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList();
        Map<String,Object> rMap ;
        Map<String,Object> data = Maps.newHashMap();
        List<JSONObject> dataRows = Lists.newArrayList();
        for(Group group : groupList){
            rMap = Maps.newHashMap();
            rMap.put("name", group.getName());
            rMap.put("id",group.getId());
            if(StringUtils.isNotEmpty(keyIds)){
                if(StringUtils.contains(keyIds, group.getId())){
                    rMap.put("checked","checked");
                }

            }
            dataRows.add(JSONObject.fromObject(rMap));
        }

        data.put("data", JSONArray.fromObject(dataRows));
        Result rs = new Result(200,"操作成功",data);
        return ajaxHtmlAppResult(rs);
    }

    public String powerDlg(){
        List<Power> powerList = (List<Power>) powerService.findByPagerAndStates(new Pager(0), new BaseEnum.StateEnum[]{BaseEnum.StateEnum.Enable}).getList();
        Map<String,Object> rMap ;
        Map<String,Object> data = Maps.newHashMap();
        List<JSONObject> dataRows = Lists.newArrayList();
        for(Power power : powerList){
            rMap = Maps.newHashMap();
            rMap.put("name","【"+power.getDepartment().getName()+"-"+power.getPost().getName()+"】");
            rMap.put("id",power.getId());
            if(StringUtils.isNotEmpty(keyIds)){
                if(StringUtils.contains(keyIds, power.getId())){
                    rMap.put("checked","checked");
                }
            }
            dataRows.add(JSONObject.fromObject(rMap));
        }

        data.put("data", JSONArray.fromObject(dataRows));
        Result rs = new Result(200,"操作成功",data);
        return ajaxHtmlAppResult(rs);
    }

    /**
     * 域list
     * @return
     */
    public String fieldlist() throws ClassNotFoundException {
        BusinessConfig businessConfig= businessConfigService.get(keyId);
        List<Map<String,Object>> mapList=getEntityFields(businessConfig);
        Map<String,Object> rMap ;
        Map<String,Object> data = Maps.newHashMap();
        List<JSONObject> dataRows = Lists.newArrayList();
        for(Map<String,Object> rmap:mapList){
            rMap = Maps.newHashMap();
            rMap.put("name",rmap.get("title").toString());
            rMap.put("id",rmap.get("filedname").toString());
            dataRows.add(JSONObject.fromObject(rMap));
        }
        data.put("data", JSONArray.fromObject(dataRows));
        Result rs = new Result(200,"操作成功",data);
        return ajaxHtmlAppResult(rs);
    }

    public String dutyDlg(){
        Users loginer = usersService.getLoginInfo();
        LogUtil.info("flowName:"+flowName);
        BusinessConfig bg = businessConfigService.getByBusinessKey(flowName);
        Set<Duty> dutyList = Sets.newHashSet();
        Map<String, Object> data = new HashMap<String, Object>();
        ProcessConfig processConfig=null;
        //填写申请单
        if(StringUtils.isEmpty(keyId)){
            //dutyList = businessConfigService.findDutyInConfig(bg, loginer);
        }else {//打开表单
            List<Task> taskList=taskService.createTaskQuery().taskCandidateOrAssigned(loginer.getId()).processInstanceBusinessKey(keyId).orderByTaskCreateTime().desc().list();
            if(taskList.size()>0){
                Task task = taskList.get(0);
                ProcessInstance processInstance = workflowService.getProIntanceByTask(task);
                processConfig = processConfigService.findConfigByActivityId(task.getProcessDefinitionId(), task.getTaskDefinitionKey());
                LogUtil.info("processConfig.getType()"+processConfig.getType());
                if(processConfig.getType()!=-1){
                    //获取上一任务节点(每个节点的候选人都配置了是否选择上一步审批人的身份,既特殊设定)
                    HistoricTaskInstanceEntity hisTask = (HistoricTaskInstanceEntity) workflowService.earlyTask(task.getProcessInstanceId());
                    dutyList.addAll(processConfigService.findDutyByConfig(processConfig));
                    if(hisTask != null){
                        // todo 获取历史流程变量
                        List<HistoricVariableInstance> histance = historyService.createHistoricVariableInstanceQuery().taskId(hisTask.getId()).variableName("curDutyId").list();
                        LogUtil.info("histance.size()"+histance.size());
                        if(histance.size()>0){
                            HistoricVariableInstanceEntity hisVarEntity = (HistoricVariableInstanceEntity) histance.get(0);
                            String dutyId = hisVarEntity.getTextValue();
                            LogUtil.info("dutyId:"+dutyId);
                            Duty duty = dutyService.get(dutyId);//获取上一步审批人审批职责
                            dutyList.addAll(processConfigService.findDutyInSpecail(processConfig,duty));
                        }
                    }else {
                        //发起流程时候的身份

                        String dutyId = (String) runtimeService.getVariable(task.getExecutionId(), "initDuty");
                        LogUtil.info("initDuty:"+dutyId);
                        Duty duty = dutyService.get(dutyId);
                        dutyList.add(duty);
                    }
                }
            }

        }
        List<JSONObject> datarows = Lists.newArrayList();
        //个人职责
        List<Duty> dList = dutyService.getDutys(loginer);

        ProcessDefinition processDefinition = workflowService.getProDefinitionByKey(flowName);
        if(processDefinition != null && StringUtils.equals(todo, "1")){
            ProcessDefinitionEntity prodefEntity = (ProcessDefinitionEntity) ((RepositoryServiceImpl)repositoryService).getDeployedProcessDefinition(processDefinition.getId());
            List<ActivityImpl> activityList= prodefEntity.getActivities();
            if(activityList.size()>=0){
                ActivityImpl activity=activityList.get(0);
                ProcessConfig processConfig2 = processConfigService.findConfigByActivityId(processDefinition.getId(), activity.getId());
                if(processConfig2!=null){
                    List<Duty> dutyList2 = processConfigService.findDutyByConfig(processConfig2);
                    dList = Collections3.intersection(dutyList2, dList);
                }
            }
        }

        Map<String,Object> rMap = null;
        if(StringUtils.isNotEmpty(keyId)){
           if(processConfig!=null && processConfig.getType()!=-1){
               for(Duty duty : dutyList){
                   if(!dList.contains(duty))continue;
                   rMap = Maps.newHashMap();
                   rMap.put("name",duty.getPower().getDepartment().getName()+"-"+duty.getPower().getPost().getName());
                   rMap.put("id",duty.getId());
                   rMap.put("checked","");
                   datarows.add(JSONObject.fromObject(rMap));
               }
           }else{
               for(Duty duty : dList){
                   rMap = Maps.newHashMap();
                   rMap.put("name",duty.getPower().getDepartment().getName()+"-"+duty.getPower().getPost().getName());
                   rMap.put("id",duty.getId());
                   rMap.put("checked","");
                   datarows.add(JSONObject.fromObject(rMap));
               }
           }
        }else{
            for(Duty duty : dList){
                rMap = Maps.newHashMap();
                rMap.put("name",duty.getPower().getDepartment().getName()+"-"+duty.getPower().getPost().getName());
                rMap.put("id",duty.getId());
                rMap.put("checked","");
                datarows.add(JSONObject.fromObject(rMap));
            }
        }

        data.put("data", JSONArray.fromObject(datarows));
        data.put("size",datarows.size());
        Result rs = new Result(200,"操作成功",data);
        return ajaxHtmlAppResult(rs);
    }

    /**
     *选择项目信息
     */
    public String project(){
        return "project";
    }

    /**
     *选择录用人
     */
    public String emp(){
        return "emp";
    }

    /**
     * 选择客户信息
     */
    public String client(){
        return "client";
    }

    /**
     * 选择联系人
     */
    public String linkman(){
        return "linkman";
    }

    /**
     * 选择合同评审
     * @return
     */
    public String contract(){
        return "contract";
    }

    /**
     * 选择投标评审
     * @return
     */
    public String tender(){
        return "tender";
    }

    /**
     * 选择部门(单选)
     * @return
     */
    public String depart(){ return "depart"; }

    /**
     * 选择部门(多选)
     * @return
     */
    public String mdepart(){ return "mdepart"; }

    /**
     * 选择岗位（单选)
     * @return
     */
    public String post(){ return "post"; }

    /**
     * 选择岗位（多选)
     * @return
     */
    public String mpost(){ return "mpost"; }

    /**
     * 选择人员(多选）
     * @return
     */
    public String user(){ return "user"; }

    /**
     * 选择人员(多选）
     * @return
     */
    public String users(){ return "users"; }

    /**
     * 选择职权（多选）
     * @return
     */
    public String power(){
        return "power";
    }

    /**
     * 选择域
     */
    public String field(){return "field";}

    /**
     * 选择角色（多选）
     * @return
     */
    public String role() {
        return "role";
    }

    /**
     * 上传文件
     * @return
     */
    public String upload(){return "upload";}
    /**
     * 字典类型
     * @return
     */
    public String dict(){return "dict";}
    /**
     * 公告对象
     * @return
     */
    public String selectionnotice(){return "selectionnotice";}
    /**
     * 竞聘演讲对象
     * @return
     */
    public String selectionspeech(){return "selectionspeech";}
    /**
     * 结果公示对象
     * @return
     */
    public String selectionpublicity(){return "selectionpublicity";}


    /**
     * 已归档的退管会年度预算申请对象
     * @return
     */
    public String annualbudget(){return "annualbudget";}

    /**
     * 职权对象
     * @return
     */
    public String duty(){return "duty";}

    /**
     * 群组对象
     * @return
     */
    public String rolecopy1(){return "rolecopy1";}

    /**
     * 选择部门
     * @return
     */
    public String dept(){
        return "dept";
    }
    /**
     * 根据部门 选岗位
     * @return
     */
    public String managePost(){
        return "managePost";
    }

    /**
     * 通过部门得到用户
     */
    public String usersByDept(){return "usersByDept";}

    /**
     * 选择人员（层级)
     * @return
     */
    public String levelUser(){
        return "levelUser";
    }
    /**
     * 党政定义方法
     */
    public String departByUsers(){return "departByUsers";}

    /**
     * 选择人员
     * @return
     */
    public String manageUser(){
        return "manageUser";
    }

    /**
     * 调动员工
     * @return
     */
    public String transferUser(){
        return "transferUser";
    }

    /**
     * 党政模块定义的部门
     * @return
     */
    public String departParty(){return "departParty";}
    /**
     * 党政模块定义
     * @return
     */
    public String powerByDepartAndUsers(){return "powerByDepartAndUsers";}
    /**
     * 党政模块定义
     * @return
     */
    public String userParty(){return "userParty";}
    /**
     * 党政模块定义

     */
    public String moneymanager(){return "moneymanager";}

    public String getFlowName() {
        return flowName;
    }

    public void setFlowName(String flowName) {
        this.flowName = flowName;
    }

    public String getIsModal() {
        return isModal;
    }

    public void setIsModal(String isModal) {
        this.isModal = isModal;
    }

    @Override
    public String getResult() {
        return result;
    }

    @Override
    public void setResult(String result) {
        this.result = result;
    }

    public String getDictName() {
        return dictName;
    }

    public void setDictName(String dictName) {
        this.dictName = dictName;
    }

    public String getIndex() {
        return index;
    }

    public void setIndex(String index) {
        this.index = index;
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    @Override
    public String getParentId() {
        return parentId;
    }

    @Override
    public void setParentId(String parentId) {
        this.parentId = parentId;
    }

    public String getDepartId() {
        return departId;
    }

    public void setDepartId(String departId) {
        this.departId = departId;
    }

    public String getStr() {
        return str;
    }

    public void setStr(String str) {
        this.str = str;
    }

    public String getUsersId() {
        return usersId;
    }

    public void setUsersId(String usersId) {
        this.usersId = usersId;
    }

    public String getPowerId() {
        return powerId;
    }

    public void setPowerId(String powerId) {
        this.powerId = powerId;
    }

    public String getPayDate() {
        return payDate;
    }

    public void setPayDate(String payDate) {
        this.payDate = payDate;
    }

    @Override
    public String getKeyId() {
        return keyId;
    }

    @Override
    public void setKeyId(String keyId) {
        this.keyId = keyId;
    }

    public String getMore() {
        return more;
    }

    public void setMore(String more) {
        this.more = more;
    }

    public String getBusinessKey() {
        return businessKey;
    }

    public void setBusinessKey(String businessKey) {
        this.businessKey = businessKey;
    }


    public String getDepId() {
        return depId;
    }

    public void setDepId(String depId) {
        this.depId = depId;
    }

    public String getDepartmentId() {
        return departmentId;
    }

    public void setDepartmentId(String departmentId) {
        this.departmentId = departmentId;
    }
}


